import {GetProps, Popover} from "antd";
import React, {FC, useRef, useState} from "react";
import {ChatContent} from "./ChatContent";
import imgPath from './fmt.webp';
import {SenderRef} from "@ant-design/x/es/sender";
import {DndContext, KeyboardSensor, MouseSensor, TouchSensor, useDraggable, useSensor, useSensors} from "@dnd-kit/core";
import {Coordinates} from "@dnd-kit/core/dist/types";
import {useModel} from "@umijs/max";
export {TChatCallbackData} from './ChatContent';

const ContentDiv: FC<{x: number, y: number, open: boolean, onClick: () => void}> = ({
  x,
  y,
  open,
  onClick,
  ...otherProps
}) => {
  const {isTour} = useModel('global');
  const {attributes, listeners, setNodeRef, transform} = useDraggable({
    id: 'draggable',
    disabled: open || isTour,
  });

  return (
    <div
      id="tourChat"
      {...otherProps}
      {...listeners}
      {...attributes}
      ref={setNodeRef}
      onClick={onClick}
      style={{
        width: 80,
        height: 80,
        // border: '1px solid #fff',
        // borderRadius: '50%',
        background: `url(${imgPath}) no-repeat center`,
        backgroundSize: '90%',
        backgroundPosition: 'center 80%',
        // backgroundColor: ' #2b3459',
        // boxShadow: '#2b3459 0px 0px 8px 0px',
        cursor: 'pointer',
        position: 'fixed',
        bottom: '2%',
        right: '2%',
        zIndex: 10,
        transform: transform
          ? `translate3d(${transform.x + x}px, ${transform.y + y}px, 0)`
          : `translate3d(${x}px, ${y}px, 0)`,
      }}
    />
  )
}

export const Chat: FC<IChatProps> = ({
  callback,
}) => {
  const [{x, y}, setCoordinates] = useState<Coordinates>({x: 0, y: 0});
  const mouseSensor = useSensor(MouseSensor, {
    activationConstraint: {
      delay: 250,
      tolerance: 10,
      distance: 3,
    },
  });
  const touchSensor = useSensor(TouchSensor, {
    activationConstraint: {
      delay: 250,
      tolerance: 10,
      distance: 3,
    },
  });
  const keyboardSensor = useSensor(KeyboardSensor, {});
  const sensors = useSensors(mouseSensor, touchSensor, keyboardSensor);
  const [, update] = useState({});
  const {current: state} = useRef({
    open: false,
  });

  const senderRef = useRef<SenderRef>(null);
  const content = (
    <ChatContent
      senderRef={senderRef}
      style={{height: '50vh', width: 500}}
      callback={callback}
      onClose={() => {
        state.open = false;
        update({});
      }}
    />
  );

  return (
    <DndContext
      sensors={sensors}
      onDragEnd={({delta}) => {
        setCoordinates(({x, y}) => {
          return {
            x: x + delta.x,
            y: y + delta.y,
          };
        });
      }}
    >
      <Popover
        content={content}
        arrow={false}
        trigger="click"
        open={state.open}
        placement="leftBottom"
        // onOpenChange={(val) => {
        //   state.open = val;
        //   update({});
        //   if (val) {
        //     setTimeout(() => {
        //       senderRef.current?.focus();
        //     }, 0);
        //   }
        // }}
      >
        <ContentDiv
          x={x}
          y={y}
          open={state.open}
          onClick={() => {
            if (state.open) {
              state.open = false;
              update({});
              return;
            }
            state.open = true;
            update({});
            setTimeout(() => {
              senderRef.current?.focus();
            }, 0);
          }}
        />
      </Popover>
    </DndContext>
  )
};

interface IChatProps {
  style?: React.CSSProperties,
  callback?: GetProps<typeof ChatContent>['callback'];
}

